package try01;

import java.util.*;

public class PermutationSequence {
	public void tester() {
		System.out.println(getPermutation(3,7));
	}
	public String getPermutation(int n, int k) {
        ArrayList <Integer> a = new ArrayList <Integer> ();
        
        for(int i = 1 ; i <= n ; i++) {
            a.add(i);
        }
        
        return p(a, k-1, "");
    }
    
    public String p(ArrayList <Integer> a, int k, String s) {
        if(a.size() == 0) {
            return s;
        }
        if(a.size() == 1) {
            if(k != 0) return "error 01";
            s = s + a.get(0);
            return s;
        }
        
        int n = a.size() - 1;
        
        int count = k / fact(n);
        k = k % fact(n);
        
        if(count >= a.size()) return "error 02";
        
        s = s + a.get(count);
        a.remove(count);
        
        return p(a, k, s);
    }
    
    public int fact(int a) {
        if(a == 0) return 0;
        int result = 1;
        for(int i =1 ; i <= a ; i++) {
            result = result * i;
        }
        return result;
    }
}
